#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <functional>
#include <memory>

#include "InerAddr.hpp"
#include "Log.hpp"

using namespace std;

// 模板方法模式
namespace socket_ns
{
    class Socket;
    const static int backlog = 8;
    using sock_sptr = shared_ptr<Socket>;
    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        USAGE_ERROR,
        LISTEN_ERROR,
    };

    // unique_ptr<Socket> listensock=make_unique<TcpSocket>();
    // listensock->BuildListenSocket();

    // unique_ptr<Socket> clientsock=make_unique<TcpSocket>();
    // clientsock->BuildClientSocket();

    // clientsock->send();
    // clientsock->Recv();
    //这种实现就叫做模板方法模式


    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void BindSocketOrDie(InetAddr &addr) = 0;
        virtual void ListenSocketOrDie() = 0;
        virtual sock_sptr Accepter(InetAddr *addr) = 0;
        virtual bool Connetcor(InetAddr &addr) = 0;

        // virtual void Recv() = 0;
        // virtual void Send() = 0;
        // virtual void Other() = 0;

    public:
        void BuildListenSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            BindSocketOrDie(addr);
            ListenSocketOrDie();
        }

        void BuildClientSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            Connetcor(addr);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int fd = -1) : _sockfd(fd)
        {
        }
        void CreateSocketOrDie() override
        {
            // 1.创建流式套接字
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket error, %s, %d\n", strerror(errno), errno);
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "socket create success, sockfd: %d\n", _sockfd);
        }
        void BindSocketOrDie(InetAddr &addr) override
        {
            // 2.bind
            //  2.0 填充sockaddr_in结构
            struct sockaddr_in local; // struct sockaddr_in 系统提供的数据类型。local是变量，用户栈上开辟空间。int a = 100; a = 20;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(addr.Port());
            local.sin_addr.s_addr = inet_addr(addr.Ip().c_str()); // htonl(INADDR_ANY);

            // 2.1 bind sockfd和网络信息(IP(?) + Port)
            int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "bind error, %s, %d\n", strerror(errno), errno);
                exit(BIND_ERROR);
            }
            LOG(INFO, "socket bind success\n");
        }
        void ListenSocketOrDie() override
        {
            // 3.tcp是面向链接的，通信之前必须建立连接;服务器是被连接的
            //  tcpserver启动了，要先等待客户的连接到来
            int n = listen(_sockfd, backlog);
            if (n < 0)
            {
                LOG(FATAL, "listen error, %s, %d\n", strerror(errno), errno);
                exit(LISTEN_ERROR);
            }
            LOG(INFO, "socket listen success\n");
        }
        sock_sptr Accepter(InetAddr *addr) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_sockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                return nullptr;
            }
            *addr = peer;
            sock_sptr sock = make_shared<TcpSocket>(sockfd);
            return sock;
        }
        bool Connetcor(InetAddr &addr) override
        {
            // 不需要显示的绑定
            struct sockaddr_in server;
            // 构建目标主机socket信息
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(addr.Port());
            server.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            int n = connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                cerr << "connect error" << endl;
                return false;
            }
            return true;
        }

    private:
        int _sockfd;
    };


}//namespace socket_ns